package persistent.prestige.console.lock;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class LockTest {

	public static final int TEST_COUNT = 6;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		List<String> lockKeys = new ArrayList<String>(TEST_COUNT);
		
		lockKeys.add("ODS0001:1");
		lockKeys.add("ODS0001:2");
		lockKeys.add("ODS0001:2");
		lockKeys.add("ODS0002:2");
		lockKeys.add("ODS0002:1");
		lockKeys.add("ODS0002:1");
		
//		for(int i = 0; i < TEST_COUNT; i ++ ) {
//			lockKeys.add(UUID.randomUUID().toString());
//		}
		
		ExecutorService threadPool = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10000));
		

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long start = System.currentTimeMillis();
		
		System.out.println(sdf.format(new Date(start)));
		
		System.out.println("start:" + start );
		CountDownLatch cdl = new CountDownLatch(TEST_COUNT);
		for( String lockKey : lockKeys ) {
			threadPool.submit(new Task(lockKey, cdl));
		}
		
		try {
			cdl.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		long end = System.currentTimeMillis();
		System.out.println(sdf.format(new Date(end)));
		System.out.println("end:" + end );
		long times = (end - start) / 1000 ;
		
		System.out.println("执行时间:" + times + " s");
		
		threadPool.shutdown();
		
		

	}
	
	
	
	
	public static void testBus(String lockKey) {
		
		
		System.out.println(Thread.currentThread() +":" + lockKey + ":" + System.currentTimeMillis() + ",准备去获取锁");
		
		try {
			LocalLock.lock(lockKey, 4 * 1000);
			
			System.out.println(Thread.currentThread() +":" + lockKey + ":" + "获取锁:" + System.currentTimeMillis());
			
			try {
				System.out.println(Thread.currentThread() +":" + lockKey  + "执行业务操作");
				Thread.sleep(2000); // 假设业务操作需要执行2s
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			System.out.println(Thread.currentThread() +":" + lockKey  + "运行结束"+ System.currentTimeMillis());
		} finally {
			LocalLock.unlock(lockKey);
			
		}
		
		
	}
	
	
	static class Task implements Runnable{
		
		private String lockKey;
		private CountDownLatch cdl;
		
		public Task(String lockKey, CountDownLatch cdl) {
			this.lockKey = lockKey;
			this.cdl = cdl;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				LockTest.testBus(lockKey);
			} finally {
				cdl.countDown();
			}
			
			
		}
		
	}

}
